package com.lvmama.conf;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lvmama.entity.system.SysRole;
import com.lvmama.system.service.SysRoleService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import com.lvmama.entity.system.Menu;
import com.lvmama.entity.system.SysUser;
import com.lvmama.system.service.MenuService;
import com.lvmama.system.service.UserService;
import com.lvmama.system.util.SerializeUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
	
	private Logger logger = Logger.getLogger(getClass());
	
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	
	@Autowired
    private SysRoleService roleService;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
    private JedisPool jedisPool;

	@Value("${tokenTimeout}")
	private Integer tokenTimeout;
	
	@Override
	protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException {
		MyUserDetail userDetail = (MyUserDetail)authentication.getPrincipal();
		HttpSession session = request.getSession();
		String token = ((WebAuthenticationDetails)authentication.getDetails()).getSessionId();

		SysUser currentUser = new SysUser();
		currentUser.setId(userDetail.getUserId());
		currentUser.setUsername(userDetail.getUsername());
		currentUser.setOperateDate(new Date());
		currentUser.setRoles(userDetail.getRoleList());
		currentUser.getRoles().get(0).setMenuList(menuService.findShowListByUser(userDetail.getUserId()));
		currentUser.setCharacterName(userDetail.getCharactorName());
		currentUser.setIsReset(userDetail.getIsReset());
		
		session.setAttribute("currentUser", currentUser);
		if (response.isCommitted()) {
			logger.info("Can't redirect");
			return;
		}
		//将登录的token存入redis，并将token返回
		//String serviceUrl = (String)request.getAttribute("service");
		Object serviceUrl = session.getAttribute("service");
		//将token放入cookie，这样就可以在第二个应用进入的时候获取，并直接返回
		Cookie cookie = new Cookie("token", token);
		response.addCookie(cookie);
		
		Jedis jedis = this.jedisPool.getResource();
		jedis.setex(token.getBytes(), tokenTimeout, SerializeUtil.serialize(currentUser));
		jedis.close();
		if(serviceUrl == null) {
			redirectStrategy.sendRedirect(request, response, "/index");
		}else {
			redirectStrategy.sendRedirect(request, response, (String)serviceUrl + "?token=" + token);
			
		}
		
	}
	public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
		this.redirectStrategy = redirectStrategy;
	}

	protected RedirectStrategy getRedirectStrategy() {
		return redirectStrategy;
	}

}